package com.example.client_anna.module;

import androidx.appcompat.app.ActionBar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.client_anna.R;
import com.example.client_anna.base.BaseActivity;
import com.example.client_anna.module.ui.ViewCarrier;
import com.example.client_anna.network.okhttp3.HttpUtilImpl;
import com.example.client_anna.util.entity.intenttransfer;
import com.example.client_anna.util.entity.User_login;
import com.example.client_anna.network.okhttp3.RequestUrl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
//登录模块
public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    private EditText editTextname;
    private EditText editTextpasswd;

    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;

    private CheckBox checkBox;

    private Boolean aBoolean = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //ScreenUtil.setDesity(this);
        setContentView(R.layout.activity_main);

        //中间白色线表示使用的方法过时，但是不影响使用
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        editTextname=(EditText)findViewById(R.id.login_username);
        editTextpasswd=(EditText)findViewById(R.id.login_userpasswd);
        checkBox=(CheckBox)findViewById(R.id.remember_pass);
        Button button=(Button)findViewById(R.id.login_submit);
        button.setOnClickListener(this);
        TextView textView = (TextView)findViewById(R.id.register_jump);
        textView.setOnClickListener(this);

        //记住密码，在重启该活动后isRemmember为true表示用户有点击记住密码选项
        //isRemember默认为false
        //把SharedPreferences对象中的值取出来填写给用户名框和密码框
        boolean isRemember = preferences.getBoolean("remember_password",false);
        if(isRemember){
            String username = preferences.getString("username","");
            String userpasswd = preferences.getString("userpasswd","");
            editTextname.setText(username);
            editTextpasswd.setText(userpasswd);
            checkBox.setChecked(true);
        }

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }

        //半透明状态栏
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //隐藏状态栏
        //View decorView = window.getDecorView();
        //decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
        case R.id.login_submit:

            if("".equals(editTextname.getText().toString())||"".equals(editTextpasswd.getText().toString())){
                Toast.makeText(MainActivity.this,"用户名或密码为空",Toast.LENGTH_SHORT).show();
            }else {
                Login_Okhttp3();
            }
            break;
        case R.id.register_jump:

            Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
            startActivity(intent);
            break;
        }
    }

    //异步okhttp3网络通信post请求
    private void Login_Okhttp3(){
        //链接的地址
        String address = RequestUrl.getUrl()+"user";
        //创建RequesstBody请求体,用于数据的提交
        RequestBody requestBody=new FormBody.Builder()
                .add("id","001")
                .add("username",editTextname.getText().toString())
                .add("userpasswd",editTextpasswd.getText().toString())
                .build();
        //调用HttpUtil网络请求，通过okhttp3进行网络访问
        HttpUtilImpl.sendOKHttpRequest(address,requestBody,new okhttp3.Callback(){
            @Override
            public void onResponse(Call call, Response response)throws IOException {
                //onResponse方法用于接收访成功后回调后的操作
                //得到response对象的具体内容
                String responseData=response.body().string();
                //分析返回的数据
                ParesJsonWithGSON(responseData);
            }
            @Override
            public void onFailure(Call call, IOException e) {
                //onFailure方法用于网络请求失败后执行的语句
                //取消请求的判断，true用户主动关闭活动页面，false超时或者网络出错
                if(e.toString().contains("closed")){
                    //用户直接关闭页面后取消请求
                    call.cancel();
                }else{
                    //网络不稳定，或者无网络
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this,"网络出错，请等待！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    //取消请求
                    call.cancel();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(aBoolean==true) {
                            Toast.makeText(MainActivity.this,"请求超时，自动登录",
                                    Toast.LENGTH_SHORT).show();
                            Login_Okhttp3();
                            aBoolean=false;
                        }else {
                            Toast.makeText(MainActivity.this,"服务器异常，请重试！",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });

            }
        });
    }

    private User_login user_login = new User_login();
    //采用GSON分析方式进行数据的转换
    private void ParesJsonWithGSON(String jsonData){

        Gson gson = new Gson();
        //字符串使用.equals判断
        if(!("".equals(jsonData))) {
            //转换json数组，使用TypeToken接收
            user_login = gson.fromJson(jsonData, new TypeToken<User_login>() {
            }.getType());

            if(!("".equals(user_login.getUserId()))) {
                Log.d(TAG, "login  " + user_login.getUserId());
                Log.d(TAG, "login  " + user_login.getName());
                Log.d(TAG, "login  " + user_login.getPicture_url());
                Log.d(TAG, "login  " + user_login.getLogin_info());
                Log.d(TAG, "login  " + user_login.getBack_info());
            }

            //异步调用的okhttp3回调函数是在子线程里面的，不能直接进行UI操作
            //要进行UI操作，需要使用runOnUiThread方法或者Handler进行处理
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if ("fail".equals(user_login.getLogin_info())) {
                        Toast.makeText(MainActivity.this, user_login.getBack_info(),
                                Toast.LENGTH_SHORT).show();
                    } else if("success".equals(user_login.getLogin_info())){
                        Toast.makeText(MainActivity.this, user_login.getBack_info(),
                                Toast.LENGTH_SHORT).show();
                        //记录用户信息
                        //Userintenttransfer(user_login.getUserId(),user_login.getName(),
                        //user_login.getPicture_url(),
                        //        user_login.getRole());
                        //记住密码
                        RememberPassword();
                        //全局记录用户信息
                        UserStateInfo();
                        Intent intent = new Intent(MainActivity.this,
                                ViewCarrier.class);
                        startActivity(intent);
                        finish();
                    }
                    else {
                        Toast.makeText(MainActivity.this, "服务器访问异常",
                                Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }

    }

    //登录成功后记住密码的实现
    private void RememberPassword(){
        //使用SharedPreferences对象来进行数据的存储
        editor = preferences.edit();
        //如果checkBox被选择则表示用户想要记住密码
        if(checkBox.isChecked()){
            //true表示记住密码
            editor.putBoolean("remember_password",true);
            editor.putString("username",editTextname.getText().toString());
            editor.putString("userpasswd",editTextpasswd.getText().toString());
        }else {
            //清除
            editor.clear();
        }
        //更新
        editor.apply();
    }

    //登录成功后，全局记录用户的状态
    private void UserStateInfo(){

        //SharedPreferences轻量型数据存储
        //存储路径/data/data/<package name>/shared_prefs/
        //参数1：文件名称，参数2：Context.MODE_PRIVATE私有数据，只能被程序本身访问
        SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = sharedPreferences.edit();

        //用户id,用户名，用户头像url，用户类型
        editor1.putString("user_id",user_login.getUserId());
        editor1.putString("user_name",user_login.getName());
        editor1.putString("user_picture",user_login.getPicture_url());
        editor1.putInt("user_role",user_login.getRole());

        editor1.apply();
        editor1.commit();
    }

    //记录登录成功后的用户信息，使用Serializable方式进行intent数据传递给需要使用的活动
    private void Userintenttransfer(String userid,String name,String picture,Integer role){

        intenttransfer intenttransfer = new intenttransfer(userid,name,picture,role);
        Intent intent = new Intent(MainActivity.this, ViewCarrier.class);
        intent.putExtra("user_info",intenttransfer);
        startActivity(intent);
    }

}